package com.example.demo;

import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleStatement;
import oracle.jdbc.dcn.DatabaseChangeRegistration;
import oracle.jdbc.pool.OracleDataSource;

import java.sql.*;
import java.util.Properties;

public class JDBCDemo {
        public  void  run() throws Exception{
            try {
                OracleDataSource dataSource;
                dataSource = new OracleDataSource();
                dataSource.setUser("usky");
                dataSource.setPassword("usky");
                dataSource.setURL("jdbc:oracle:thin:@172.16.1.65:1521:orcl");

                OracleConnection conn = (OracleConnection) dataSource.getConnection();

                Properties prop = new Properties();
                prop.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS,"true");
                prop.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION,"true");
                DatabaseChangeRegistration dcr = conn.registerDatabaseChangeNotification(prop);


                DCNDemoListener list = new DCNDemoListener(this);
                dcr.addListener(list);

                Statement stmt= conn.createStatement();
                ((OracleStatement)stmt).setDatabaseChangeRegistration(dcr);
                //结果集
                ResultSet rs = stmt.executeQuery("select * from p_transfer_cus_change_reg");
                //依次输出结果集内容
                while (rs.next())
                {}
                String[] tableNames = dcr.getTables();
                for(int i=0;i<tableNames.length;i++)
                    System.out.println(tableNames[i]+" is part of the registration.");

                while(rs.next()){
                    System.out.println(
                            rs.getInt(1) + "\t"
                                    +rs.getString(2)+"\t"
                                    +rs.getString(3)+"\t"
                                    +rs.getInt(4)+"\t"
                                    +rs.getString(5)+"\t");
                }
                //依次关闭结果集，操作对象，数据库对象
                if(rs!=null){
                    rs.close();
                }
                if(stmt!=null){
                    stmt.close();
                }
                if(conn!=null){
                    conn.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
